﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mobile.Models;
using System.Data.SqlClient;
using System.Configuration;
using Mobile.MainService;
using System.Text.RegularExpressions;

namespace Mobile.Controllers
{
    public class GuestUIController : Controller
    {
        Service sv = new Service();
        //Party pt = new Party();
  
        // POST: /GuestUI
        [HttpPost]
        public ActionResult Index(FormCollection collection)
        {
            string accessCode = collection.Get("partyCode");
            string partyID = null;
            if (accessCode != null)
            {
                partyID = GetPartyID(accessCode);
            }
            if (String.IsNullOrEmpty(partyID))
            {
                partyID = "55f55676-a894-4b65-8060-5c93c649efa2";
            }

            Session["PartyID"] = partyID;

            //pt = new Party { PartyID = partyID, Description = partyID, EndTime = new DateTime(), queue = new Queue { partyID = partyID } };
            //return RedirectToAction("Playlist", "GuestUI", new { id=partyID });
            return RedirectToAction("Playlist");
        }

        public PartialViewResult GetNowPlaying()
        {
            string partyID = getSessionPartyID();
            
            if (String.IsNullOrEmpty(partyID)) 
                throw new Exception("No PartyID in GetNowPlaying");
            
            return PartialView("_GetNowPlaying", new Queue { partyID = partyID });
        }

        /* RefreshQueue PartialView Update
         * Desc: This should update all data Models with information from Mikahil's Webservice
         * 
         * @return PartialViewResult _Playlist.cshtml (in shared folder)
         */
        // GET: /GuestUI./RefreshQueue?partyID="3231"
        public PartialViewResult GetQueue()
        {
            string partyID = getSessionPartyID();

            if (String.IsNullOrEmpty(partyID))
                throw new Exception("No PartyID in GetQueue");

            //Response.AddHeader("Refresh", "10");
            return PartialView("_Playlist", new Queue { partyID = partyID });
        }

        /* AddSong()
         *  
         * Desc: This action is called to return the view of the AddSong Page
         *      the list of songs will be returned in a partial view 
         *      
         * @return AddSong View
         */
        // GET: /GuestUI./AddSong?partyID="3231"
        public ActionResult AddSong()
        {
            string partyID = getSessionPartyID();
            if (String.IsNullOrEmpty(partyID))
                throw new Exception("No PartyID in AddSong");

            return View(new Party { PartyID = partyID });
        }

        /* Playlist View ActionResult
         * 
         * Desc: 
         * 
         * @return Playlist View
         */
        public ActionResult Playlist()
        {
            string partyID = getSessionPartyID();
            if (String.IsNullOrEmpty(partyID))
                throw new Exception("No PartyID in Playlist");
            

            return View(new Queue { partyID = partyID });
        }

        /* UpvoteButton Action Method
        * 
        * Desc: Takes Song ID from ActionLink call and tells service to upvote
        * 
        * @param string SongID: the songID that has been updated
        * @return: partial view Queue
        */
        public PartialViewResult UpvoteButton(string songID)
        {
            string partyID = getSessionPartyID();
            if (String.IsNullOrEmpty(partyID))
                throw new Exception("No PartyID in UpvoteButton");

            if (ProcessVote(songID))
                sv.UpvoteSong(partyID, songID);

            return GetQueue();
        }

        private bool ProcessVote(string songID)
        {
            int votes = (int?)Session["Votes"] ?? 10;

            if (votes > 0)
            {
                votes--;
                Session["Votes"] = votes;
                return true;
            }
            else
                return false;
        }

        public ActionResult RequestSongButton(string songID)
        {
            string partyID = getSessionPartyID();
            if (String.IsNullOrEmpty(partyID))
                throw new Exception("No PartyID in UpvoteButton");

            if (ProcessVote(songID)) //we're going to fail silently
                sv.UpvoteSong(partyID, songID);

            return RedirectToAction("Playlist");
        }

        /* DownvoteButton Action Method
        * 
        * Desc: Takes Song ID from ActionLink call and tells service to downvote
        * 
        * @param string SongID: the songID that has been updated
        * @return: partial view Queue
        */
        public PartialViewResult DownvoteButton(string songID)
        {
            string partyID = getSessionPartyID();
            if (String.IsNullOrEmpty(partyID))
                throw new Exception("No PartyID in UpvoteButton");

            if (ProcessVote(songID))
                sv.DownvoteSong(partyID, songID);

            return GetQueue();

        }

        public string GetPartyID(string accessCode)
        {
            var match = Regex.Match(accessCode, "^##(.*)#$");

            if (match.Success)
                return match.Groups[1].Value;

            SqlDataReader reader;
            try
            {
                SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["NextrackConn"].ConnectionString);
                myConnection.Open();

                //Get ID
                using (SqlCommand command = new SqlCommand("SELECT * FROM Parties Where Access_Code=@Access_Code", myConnection))
                {
                    command.Parameters.Add(new SqlParameter("Access_Code", accessCode));
                    reader = command.ExecuteReader();

                    reader.Read();
                    return reader["ID"].ToString();
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            //return null;
        }

        public string getSessionPartyID()
        {
            string id = (string) Session["PartyID"];
            if (string.IsNullOrEmpty(id))
            {
               // RedirectToAction("Index", "Home", new { message = "Please provide a correct PartyID" });
            }

            return id;
        }


    }

}
